<?php
namespace common\repositories\budget;

use common\entities\budget\BudgetEntity;
use common\entities\ContractEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;

/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 16/9/9
 * Time: 上午11:48
 */
class BudgetRepository extends BaseRepository {
    /**
     * 预算列表
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getAllList($freeApplicationCodes)
    {
        return BudgetEntity::find()
            ->where(['not in', 'myscrm_budget.appCode', $freeApplicationCodes])
            ->orderBy(['appCode' => SORT_DESC])
            ->all();
    }

    /**
     * 预算保存
     * @param $year
     * @param $data
     * @return bool
     */
    public function save($year, $data) {
        //判断年份是否存在
        $budget = BudgetEntity::find()->where(["year" => $year])->one();
        if (empty($budget)) {
            $budget = new BudgetEntity();
        }
        $budget->setAttributes($data);
        $budget->modified_by = \Yii::$app->user->identity->username;
        $budget->updated_at = date("Y-m-d H:i:s");
        if ($budget->isNewRecord) {
            $budget->year = $year;
            $budget->id = StringHelper::uuid();
            $budget->created_at = date("Y-m-d H:i:s");
        }
        if (false === $budget->save()) {
            return $this->setAndReturn("-1", $budget->getAllFirstErrorMessage());
        }
        return true;
    }

    public function deleteBudgetByYear($year)
    {
        try {
            BudgetEntity::deleteAll(['year' => $year]);
            return true;
        }catch (\Exception $e){
            \Yii::error((string)$e);
            return false;
        }
    }

    public function addBudget($year, $data)
    {
        //循环，组建SQL
        $sql = '';
        $pars = [];
        $pars[':CreatedOn'] = date("Y-m-d H:i:s");
        $pars[':CreatedBy'] = \Yii::$app->user->identity->userguid;
        $pars[':year'] = $year;

        foreach ($data as $budget){
            foreach ($budget as $key => $value){
                if(intval($key) > 0){
                    $sql .= "INSERT INTO `myscrm_budget` (`budgetId`, `CreatedOn`, `CreatedBy`, `year`, `month`, `appCode`, `money`) VALUES (:budgetId_" . $budget['appCode']. $key . ", :CreatedOn, :CreatedBy, :year, :month_" . $budget['appCode']. $key . ", :appCode_" . $budget['appCode']. $key . ", :money_" . $budget['appCode'] . $key . ");";
                    $pars[':budgetId_' . $budget['appCode'] . $key] = StringHelper::uuid();
                    $pars[':month_' . $budget['appCode'] . $key] = $key;
                    $pars[':appCode_' . $budget['appCode'] . $key] = $budget['appCode'];
                    $pars[':money_' . $budget['appCode'] . $key] = $value;

                }
            }
        }

        if($sql != ''){
            try {
                $db = BudgetEntity::getDb();
                $addResult = $db->createCommand($sql, $pars)->execute();

                if($addResult > 0){
                    return true;
                }
            }catch (\Exception $e){
                \Yii::error((string)$e);
                return $this->setAndReturn(__LINE__, '批量插入预算失败');
            }

        }

        return false;
    }
}